const Base = require('./base.js');
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'id';
        const shelves_beg = this.get('begin') || '';
        const shelves_end = this.get('end') || '';
        const name = this.get('title') || '';
        let seachdata = { id: ['>', 0]}, timesearch = {};
        if (name) {
            seachdata.name = ['like', `%${name}%`];
        }

        if (shelves_beg || shelves_end) {
            if (shelves_beg) {
              timesearch['egt'] = shelves_beg;
            }
            if (shelves_end) {
              timesearch['elt'] = shelves_end;
            }
            seachdata.update_time = timesearch;
        }

        const model = this.model('question');
        const c_model = this.model('question_content');
        let data = await model.where(
            seachdata
        ).order([sortField]).page(page, size).countSelect();
        for (let l of data.data) {
            l.joinnum = await this.model('question_user').where({question_id:l.id}).count('distinct userid');
            l.list=await c_model.where({question_id: l.id}).select();
            for(let i of l.list){
                i.option=JSON.parse(i.ques_option);
              }
          }
        return this.success(data);
    }

    async saveAction() {
        const model = this.model('question');
        let values = this.post();
        let id = this.post('id')||0;
        let content = this.post('list');
        if (id>0) {
    return this.fail(501, '非法参数id');
        } else {
            values['id']=0;
            await model.transaction(async () => {
                id = await model.add(values);
                //那如果一个事务中涉及到多个model：
                let c_model = this.model('question_content').db(model.db());
                if (content) {
                    let qnum=1;
                  for (let i = 0; i < content.length; i++) {
                    console.log('')
                    let l = content[i];
                      await c_model.add({
                        question_id: id,
                        content_num: i+1,
                        content_type:l.content_type==='text'?'text':'ques',
                        text_info:l.content_type==='text'?l.text_info:'',
                        ques_title:l.content_type==='text'?'':l.ques_title,
                        ques_num:qnum,
                        ques_type:l.content_type==='text'?'':l.ques_type,
                        ques_option:JSON.stringify(content[i].option)
                      });
                      qnum=l.content_type==='text'?qnum:1+qnum;
                  }
                }
              })

            values['id'] = id;
        }
        return this.success(values);
    }
    async updateAction() {
        const model = this.model('question');
        let values = this.post();
        let id = this.post('id')||0;
        const answernum=await this.model('question_option').where({question_id:id}).count();
        if(answernum>0) return this.fail(400,'问卷已经分发参与，无法再修改');
        let content = this.post('list');
            await model.transaction(async () => {
                await model.update(values);
                //那如果一个事务中涉及到多个model：
                let c_model = this.model('question_content').db(model.db());
                await model.update(values);
                await c_model.where({ question_id: id }).delete();
                if (content) {
                    let qnum=1;
                  for (let i = 0; i < content.length; i++) {
                    console.log('')
                    let l = content[i];
                      await c_model.add({
                        question_id: id,
                        content_num: i+1,
                        content_type:l.content_type==='text'?'text':'ques',
                        text_info:l.content_type==='text'?l.text_info:'',
                        ques_title:l.content_type==='text'?'':l.ques_title,
                        ques_num:qnum,
                        ques_type:l.content_type==='text'?'':l.ques_type,
                        ques_option:JSON.stringify(content[i].option)
                      });
                      qnum=l.content_type==='text'?qnum:1+qnum;
                  }
                }
              })

        return this.success(values);
    }

    async readAction() {
        const model = this.model('question');
        const c_model = this.model('question_content');
        const id = this.get('id');
        let data=await model.where({id: id}).find();
        data.list=await c_model.where({question_id: id}).select();
        for(let i of data.list){
            i.option=JSON.parse(i.ques_option);
          }
        return this.success(data);
    }

    async deleteAction() {
        const model = this.model('question');
        const id = this.post('id');
        let data;
        await model.transaction(async () => {
            data = await model.where({ id: id }).delete();
            //那如果一个事务中涉及到多个model：
            let menumodel = this.model('question_content').db(model.db());
            await menumodel.where({ question_id: id }).delete();
            })
        return this.success(data);
    }

    async saveAnswerAction() {//保存答案
      const u_model = this.model('question_user');
      let values = this.post();
      let content = this.post('list');
      let id = this.post('question_id')||0;
      let aid=0;
      if (id<1) {
  return this.fail(501, '缺少参数问题id');
      } else {
          values['id']=0;
          values['question_id']=id;
          values['userid']=think.userId;
          let c_values=[];
          if (content) {
            for (let i = 0; i < content.length; i++) {
              let l = content[i];
              for(let op of l.option){
                let c_v={
                  question_id:id,
                  question_content_id:l.question_content_id,
                  option:op.text,
                  user_id:think.userId
                }
                c_values.push(c_v);
              }
              
            }
          }

          await model.transaction(async () => {
            aid = await model.add(values);
              //那如果一个事务中涉及到多个model：
              let c_model = this.model('question_option').db(model.db());
              await c_model.addMany(c_values);
             
            })

          values['id'] = aid;
      }
      return this.success(values);
    }

    async joinListAction() {//参与列表
      const model = this.model('question_user');
      const integral_model = this.model('task_integral');
      const page = this.get('page') || 1;
      const size = this.get('size') || 20;
      const id=this.get('id') || 0;
   const datas = await model.join({ table: 'user',  join: 'left', as:'u', on: ['userid', 'id'] })
    .where( {question_id:id,'u.nickname':['!=',null]}).field("u.id as userid, u.name, u.gender,u.city,u.mobile, u.nickname,hiolabs_question_user.update_time").group('u.id').page(page, size).countSelect();
  for(const item of datas.data){
      item.nickname = Buffer.from(item.nickname, 'base64').toString();
      const integral_u=await integral_model.where({user_id:item.userid,task_type:3}).find();
      item.is_follow=think.isEmpty(integral_u)?0:1;

  }

      return this.success(datas);
  }
  async staticAction() {//问卷统计
    const model = this.model('question');
    const c_model = this.model('question_content');
    const o_model = this.model('question_option');
    const id=this.get('id') || 0;
    const datas = await model.join({ table: 'question_content',  join: 'inner', as:'c', on: ['id', 'question_id'] })
    .where( {'c.question_id':id,content_type:'ques'}).field("hiolabs_question.name,c.ques_title,c.ques_option,c.id as c_id").order('c.ques_num').select();
    for(const item of datas){
      let option=JSON.parse(item.ques_option);
      item.optiondetail=[];
      let total = await o_model.where({question_id:id,question_content_id:item.c_id}).count('distinct user_id');
      // if(total>0){
        for(const it of option){
          let sum= await o_model.where({question_id:id,question_content_id:item.c_id,option:it.text}).count();
          let ve={
            text:it.text,
            num:total>0?sum+'票':'0票',
            per:total>0?parseFloat(sum*100/total).toFixed(2)+'%':'0%'
          };
          item.optiondetail.push(ve);
        }
      // }
    }

    return this.success(datas);
}


};